<template>
    <Modal
        v-model="isVisible"
        :mask-closable="false"
        :width="700"
        :title="title"
        class-name="license-modal">
        
        <Form ref="changePwdForm" :model="passwordDetail" :rules="formRules" :label-width="120" :show-message="false">

            <Row class="add-pwd-line" type="flex" align="middle">
                    <Col span="21">
                        <FormItem label="被授权人姓名：" prop="name" class="add-pwd-form-item">
                            <Input v-model.trim="passwordDetail.name" placeholder="被授权人姓名" :maxlength="50" disabled></Input>
                        </FormItem>
                    </Col>
                    <Col span="21" v-if="!isFinger">
                        <FormItem label="被授权人电话：" prop="phonenumber" class="add-pwd-form-item">
                            <Input v-model.trim="passwordDetail.phonenumber" placeholder="被授权人电话" :maxlength="11" :disabled="!isAdmin">
                                <Select v-model="passwordDetail.country_code" slot="prepend" style="width: 110px">
                                    <Option v-for="item in CountryCodes" :key="item.code" :value="item.code">{{item.country}}</Option>
                                </Select>
                            </Input>
                        </FormItem>
                    </Col>
            </Row>

            <FormItem label="密码类型：" prop="pwdType" class="add-pwd-form-item">
                    <Select v-model="passwordDetail.pwdType" style="width:165px" v-show="!isAdmin && !isFinger">
                        <Option v-for="item in pwdTypes" :value="item.type" :key="item.type" disabled>{{ item.text }}</Option>
                    </Select>
                    <span v-show="isAdmin">离线管理员密码</span>
                    <span v-show="isFinger">指纹密码</span>
            </FormItem>

            <FormItem label="密码有效期：" prop="pwdPeriodType" class="add-pwd-form-item">
                    <Select v-model="passwordDetail.pwdPeriodType" style="width:165px" @on-change="selectPwdPeriod" v-show="!isAdmin">
                        <Option v-for="item in pwdPeriodTypes" :value="item.type" :key="item.type">{{ item.text }}</Option>
                    </Select>
                    <span v-show="isAdmin">永久有效</span>
            </FormItem>

            <div class="changePwdTip" v-show="isAdmin">
                离线管理员密码只支持在门锁本地操作删除。为避免风险，建议使用在线管理员密码
            </div>

            <FormItem label="" v-show="!isAdmin">
                    <Row>
                        <Col span="9">
                            <FormItem prop="pwdStartTime">
                                <DatePicker type="datetime" v-model="passwordDetail.pwdStartTime" format="yyyy-MM-dd HH:mm" placeholder="开始时间" style="width: 100%" :options="pwdTimeOptions" :readonly="passwordDetail.pwdType == 2" :disabled="passwordDetail.pwdType == 2" @on-open-change="onOpenChange" ></DatePicker>
                            </FormItem>
                        </Col>
                        <Col span="2" style="text-align: center">-</Col>
                        <Col span="9">
                            <FormItem prop="pwdEndTime">
                                <DatePicker type="datetime" v-model="passwordDetail.pwdEndTime" format="yyyy-MM-dd HH:mm" placeholder="结束时间" style="width: 100%" :options="pwdTimeOptions" @on-open-change="onOpenChange"></DatePicker>
                            </FormItem>
                        </Col>
                    </Row>
            </FormItem>

        </Form>

        <div slot="footer">
            <Button type="ghost" size="large" @click="isVisible=false">取消</Button>
            <Button type="primary" :loading="isLoading" size="large" @click="changePwd">确定</Button>
        </div>
    </Modal>
</template>

<script>
import dayjs from 'dayjs'
import { http, api } from '@/libs/http'
import validate from '@/libs/validate'
import { CountryCodes } from '@/libs/const'
export default {
  data () {
    return {
      pwdTypes: [{ type: 1, text: '在线密码' }, { type: 2, text: '离线密码' }, { type: 3, text: '不授权' }],
      pwdPeriodTypes: [
        { type: 0, text: '请选择时长' },
        { type: 0.5, text: '半个月' },
        { type: 1, text: '一个月' },
        { type: 3, text: '三个月' },
        { type: 6, text: '六个月' },
        { type: 12, text: '十二个月' },
        { type: -1, text: '自定义' }
      ],
      formRules: {
        phonenumber: [{ validator: validate.validPhone }]
      },
      isLoading: false,
      CountryCodes
    }
  },

  props: {
    passwordDetail: {
      // 密码详情对象
      require: true,
      type: Object
    },
    lockDetail: {
      // 设备详情对象
      require: true,
      type: Object
    },
    visible: {
      // 弹窗是否显示
      require: true,
      type: Boolean
    },
    isAdmin: {
      // 是否是id为3000的管理员密码的修改
      type: Boolean,
      default: false
    },
    isFinger: {
      // 是否是指纹密码
      type: Boolean,
      default: false
    }
  },

  mounted () {
    this.$nextTick(() => {
      let maskArr = document.getElementsByClassName('license-modal')
      let len = maskArr.length
      for (let i = 0; i < len; i++) {
        maskArr[i].parentNode.getElementsByClassName('ivu-modal-mask')[0].style.zIndex = 1004
      }
    })
  },

  computed: {
    isVisible: {
      get () {
        return this.visible
      },

      set (val) {
        // 设置关闭，触发调用父级方法
        this.$emit('on-close', val)
      }
    },

    title () {
      return this.isFinger ? '修改指纹有效期' : '修改密码有效期'
    },

    pwdTimeOptions () {
      return {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000
        }
      }
    }
  },

  methods: {
    onOpenChange (flag) {
      // 当用户手动选择日期的时候密码有效期自动显示为自定义
      if (flag) this.$set(this.passwordDetail, 'pwdPeriodType', -1)
    },
    selectPwdPeriod (type) {
      if (this.passwordDetail.pwdType === 1) {
        // 仅有当该密码为普通密码的时候才修改起始时间
        this.passwordDetail.pwdStartTime = dayjs().toDate()
      }

      switch (type) {
        case -1:
          this.passwordDetail.pwdEndTime = ''
          break
        case 0.5:
          this.passwordDetail.pwdEndTime = dayjs()
            .add(15, 'days')
            .toDate()
          break
        case 1:
        case 3:
        case 6:
        case 12:
          this.passwordDetail.pwdEndTime = dayjs()
            .add(type, 'months')
            .toDate()
          break
      }
    },
    changeAdminPassword () {
      // 修改id为3000的管理员密码

      this.$refs['changePwdForm'].validate(valid => {
        if (!valid) {
          this.$Message.warning('电话号码格式错误')
          return
        }

        let { roomId, device_id } = this.lockDetail // 获取room_id和device_id
        let { name, phonenumber } = this.passwordDetail // 获取姓名和电话号码

        let params = {
          name,
          phonenumber,
          permission_status: 2,
          CMD: 3
        }
        this.isLoading = true
        http.request(this, api.password_admin_activation_passwords_send, [roomId, device_id], params, (res, err) => {
          this.isLoading = false
          if (err) {
            return
          }

          this.$Message.warning('管理员密码下放成功')
          this.isVisible = false
        })
      })
    },
    changePwd () {
      // 修改激活码密码或者普通密码
      if (this.passwordDetail.pwdEndTime - this.passwordDetail.pwdStartTime <= 0) {
        this.$Message.info('结束时间不能小于开始时间')
        return
      }
      if (this.isAdmin) {
        this.changeAdminPassword()
      } else {
        this.changeSimplePassword()
      }
    },
    changeSimplePassword () {
      let finalApi = api.password_update_active // api默认为更新激活码

      let title = '离线密码'

      const { roomId, device_id } = this.lockDetail // 获取room_id和device_id

      const { id, name, phonenumber, country_code } = this.passwordDetail

      let params = {
        permission_status: 2,
        permission_begin: this.passwordDetail.pwdStartTime.valueOf(),
        permission_end: this.passwordDetail.pwdEndTime.valueOf(),
        name,
        phonenumber,
        country_code
      }

      if (this.passwordDetail.pwdType === 1) {
        // 如果密码类型为普通密码,或者为指纹密码
        finalApi = api.password_update
        title = '在线密码'

        params = {
          name,
          permission_begin: Math.floor(this.passwordDetail.pwdStartTime.valueOf()),
          permission_end: Math.floor(this.passwordDetail.pwdEndTime.valueOf()),
          permission_status: 2,
          phonenumber,
          country_code
        }

        if (this.isFinger) {
          title = '指纹密码'
          finalApi = api.finger_password_update
          params.permission_begin = this.passwordDetail.pwdStartTime.valueOf()
          params.permission_end = this.passwordDetail.pwdEndTime.valueOf()
          delete params.phonenumber
          delete params.name
        }
      }
      this.isLoading = true
      http.request(this, finalApi, [roomId, device_id, id], params, (res, err) => {
        this.isLoading = false
        if (err) {
          return
        }
        this.$Message.success(`更新${title}指令已下发`)
        this.isVisible = false
        this.$emit('refresh')
      })
    }
  }
}
</script>
<style lang='less'>
.add-pwd-line {
    border-bottom: 1px solid #ddd;
    margin: 0 0 10px;
    padding: 0 0 5px;
}
.add-pwd-form-item {
    margin-bottom: 5px;
}
.changePwdTip {
    padding-left: 20px;
    color: red;
}
</style>
